iT邦幫忙

2022 iThome 鐵人賽

DAY 3
0
Software Development

戀戀 Elixir系列 第 3

三. Anonymous Functions

  • 分享至 

  • xImage
  •  

For each task, return an anonymous function that can be invoked from the calling scope.

All functions should expect integer arguments. Integers are also suitable for performing bitwise operations in Elixir.

1. Create an adder

Implement Secrets.secret_add/1. It should return a function which takes one argument and adds to it the argument passed in to secret_add.

2. Create a subtractor

Implement Secrets.secret_subtract/1. It should return a function which takes one argument and subtracts from it the secret passed in to secret_subtract.

3. Create a multiplier

Implement Secrets.secret_multiply/1. It should return a function which takes one argument and multiplies it by the secret passed in to secret_multiply.

4. Create a divider

Implement Secrets.secret_divide/1. It should return a function which takes one argument and divides it by the secret passed in to secret_divide.

5. Create an "and"-er

Implement Secrets.secret_and/1. It should return a function which takes one argument and performs a bitwise and operation on it and the secret passed in to secret_and.

6. Create an "xor"-er

Implement Secrets.secret_xor/1. It should return a function which takes one argument and performs a bitwise xor operation on it and the secret passed in to secret_xor.

7. Create a function combiner

Implement Secrets.secret_combine/2. It should return a function which takes one argument and applies to it the two functions passed in to secret_combine in order.


https://exercism.org/tracks/elixir/exercises/secrets

use Bitwise

defmodule Secrets do
  def secret_add(secret) do
    &(&1 + secret)
  end

  def secret_subtract(secret) do
    &(&1 - secret)
  end

  def secret_multiply(secret) do
    &(&1 * secret)
  end

  def secret_divide(secret) do
    # &(trunc(&1 / secret))
    &(div(&1, secret))
  end

  def secret_and(secret) do
    &(&1 &&& secret)
  end

  def secret_xor(secret) do
    &(bxor(secret, &1))
  end

  def secret_combine(secret_function1, secret_function2) do

    &(secret_function2.(secret_function1.(&1)))
  end
end

上一篇
二. Pattern Matching
下一篇
四.Booleans
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言